import styles from './index.module.scss'
import Dialog from '@c/dialog'
import Button from '@c/button'
import { userInfo } from '@/store'
import { useRecoilValue } from 'recoil'
import { useRef, useEffect, useState, useMemo } from 'react'
import { hashMD5 } from '@/utils/cryptojs'
import { openNewTab } from '@/utils/utils'
import cm from 'classnames'
import { generatePayQrCode, getPayResult, payCenter, maLaiPayOrder, clearOrderCache } from '@/api/vip'
import QRCode from 'qrcode'
import dayjs from 'dayjs'
import FetchLoading from '@c/fetch-loading'
import Loading from '../pay-loading'
import { paySuccessReport } from '@/utils/report'

const payArr = [
  {
    value: 1,
    icon: '/images/wechat-1.png',
    name: '微信'
  },
  {
    value: 2,
    icon: '/images/alipay-1.png',
    name: '支付宝'
  },
  {
    value: 3,
    icon: '/images/paypal-1.png',
    name: 'paypal'
  }
]
const MaLaiArr = [
  {
    value: 5,
    icon: '/images/touchNGo-1.png',
    name: 'touchNGo'
  },
  {
    value: 4,
    icon: '/images/boost-1.png',
    name: 'Boost'
  },
  {
    value: 6,
    icon: '/images/grabPay-1.png',
    name: 'GrabPay'
  }
]

const reportData = (data, user) => {
  const { email, expireTime } = user
  const lastTime = dayjs(expireTime * 1000).diff(new Date())
  let value = data.price
  try {
    value = data.price / 100
  } catch (error) {}
  paySuccessReport({
    user_is_vip: lastTime > 0 ? 'true' : 'false',
    pay_success_time: new Date().toLocaleString(),
    email,
    pay_price: `支付${data.price}分`,
    value,
    currency: 'RMB'
  })
}

const Index = props => {
  const { vipData, currKey = 0, onClose } = props
  const [selected, setSelected] = useState(currKey)
  const [payType, setPayType] = useState(1)
  const [paySuccess, setPaySuccess] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [url, setUrl] = useState('')
  const [orderId, setOrderId] = useState(0)
  const user = useRecoilValue(userInfo)
  const refQrcode = useRef(null)
  const timer = useRef(null)
  const timerResult = useRef(null)
  const timerSuccess = useRef(null)
  const loadingTimer = useRef(null)
  const clearLoadingTimer = () => {
    if (loadingTimer.current) {
      clearTimeout(loadingTimer.current)
    }
  }
  const cleatSuccTimer = () => {
    if (timerSuccess.current) {
      clearTimer(timerSuccess.current)
    }
  }
  const clearTimer = () => {
    if (timer.current) {
      clearInterval(timer.current)
    }
  }
  const clearResultTimer = () => {
    if (timerResult.current) {
      clearInterval(timerResult.current)
    }
  }

  // 支付结果查询
  const getResult = async orderId => {
    const res = await getPayResult({
      orderId,
      sign: hashMD5(orderId)
    })
    //支付成功
    if (res.code === 0 && res.data.result === 'success') {
      clearOrderCache()
      setPaySuccess(true)
      clearResultTimer()
      clearTimer()
      reportData(res.data, user)
      timerSuccess.current = setTimeout(() => {
        onClose()
        clearResultTimer()
        timerSuccess.current = null
        window.location.reload()
      }, 3000)
    }
  }

  //预下单，生成二维码
  const getQrCode = async () => {
    const pCode = vipData[selected].pCode
    const res = await generatePayQrCode({
      pCode,
      sign: hashMD5(pCode),
      payWay: payType
    })
    if (res.code === 0) {
      setIsLoading(false)
      const { orderId, url, pollingTotal } = res?.data || {}
      clearTimer()
      clearResultTimer()
      setOrderId(orderId)
      try {
        QRCode.toCanvas(refQrcode.current, url, { margin: 0 })
      } catch (error) {}
      timer.current = setInterval(() => {
        getQrCode()
      }, pollingTotal * 1000)
    }
  }

  // 马来预下单
  const getMaLaiCode = async () => {
    const pCode = vipData[selected].pCode
    const res = await maLaiPayOrder({
      pCode,
      sign: hashMD5(pCode),
      payWay: payType
    })
    if (res.code === 0) {
      setIsLoading(false)
      const { orderId, data } = res?.data || {}
      clearTimer()
      clearResultTimer()
      setOrderId(orderId)
      try {
        QRCode.toCanvas(refQrcode.current, data, { margin: 0 })
      } catch (error) {}
      timer.current = setInterval(() => {
        getQrCode()
      }, 180 * 1000)
    }
  }
  // paypal下单
  const paypalGet = async () => {
    const pCode = vipData[selected].pCode
    const res = await payCenter({
      pCode,
      deviceType: 3,
      userId: user?.id
    })
    if (res.code === 0) {
      setIsLoading(false)
      const { orderId, url } = res?.data || {}
      setUrl(url)
      setOrderId(orderId)
    }
  }

  // 去paypal支付
  const toPaypal = async () => {
    if (isLoading) {
      return
    }
    openNewTab(url)
  }
  // 生成链接
  useEffect(() => {
    setIsLoading(true)
    clearLoadingTimer()
    if (payType == 3) {
      loadingTimer.current = setTimeout(() => {
        paypalGet()
      }, 1000)
      return
    } else if ([4, 5, 6].includes(payType)) {
      loadingTimer.current = setTimeout(() => {
        getMaLaiCode()
      }, 1000)
    } else {
      loadingTimer.current = setTimeout(() => {
        getQrCode()
      }, 1000)
    }
  }, [payType, selected])

  // 开启查询支付结果
  useEffect(() => {
    if (!orderId) {
      return
    }
    clearResultTimer()
    timerResult.current = setInterval(() => {
      getResult(orderId)
    }, 6000)
  }, [orderId])

  // 清空定时器
  useEffect(() => {
    return () => {
      clearTimer()
      clearResultTimer()
      cleatSuccTimer()
    }
  }, [])

  const quanyiMemo = useMemo(() => {
    const expire = dayjs(user.expireTime * 1000)
    const lastTime = expire.diff(dayjs(new Date()), 'day')
    if (lastTime >= 0 && lastTime <= 2) {
      return {
        img: (
          <div className={styles.vipImg}>
            <img loading="lazy" className={styles.vipLogo} src="/images/vip-active.png" alt="vip" />
          </div>
        ),
        time: <p>VIP权益还有{lastTime + 1}天到期，续费VIP体验不间断！</p>
      }
    } else if (lastTime > 2) {
      return {
        img: (
          <div className={styles.vipImg}>
            <img loading="lazy" className={styles.vipLogo} src="/images/vip-active.png" alt="vip" />
          </div>
        ),
        time: <p>VIP权益至{expire.format('YYYY/MM/DD')}</p>
      }
    } else {
      if (!user?.token) {
        return {
          img: <div className={styles.vipImg}></div>,
          time: <p>新用户注册免费领VIP</p>
        }
      }
      if (!user.expireTime) {
        return {
          img: <div className={styles.vipImg}></div>,
          time: null
        }
      }
      return {
        img: (
          <div className={styles.vipImg}>
            <img loading="lazy" className={styles.vipLogo} src="/images/vip-inactive.png" alt="vip" />
          </div>
        ),
        time: <p>VIP权益已过期{Math.abs(lastTime) + 1}天，开通尊享VIP体验！</p>
      }
    }
  }, [user])

  return (
    <Dialog className={cm(styles.content, payType === 3 ? styles.contentPaypal : '')}>
      <img loading="lazy" alt="关闭" src="/images/close.png" className={styles.close} onClick={onClose} />
      <div className={styles.vipLeft}>
        <div className={styles.vipUseInfo}>
          {quanyiMemo.img}
          <div className={styles.vipName}>
            <p className="textEllipsis">{user?.email}</p>
            {quanyiMemo.time}
          </div>
        </div>
        <div className={styles.vipChoose}>
          <img loading="lazy" src="/images/vip.png" alt="vip" />
          <span className={styles.span1}>请选择会员方案</span>
          <span className={styles.span2}>权益适用于网页端/TV端/手机端（支持多设备同时在线）</span>
        </div>
        <div className={styles.vipTaocan}>
          {vipData.map((item, index) => {
            return (
              <div
                className={cm(styles.vipTaocanItem, index === selected ? styles.active : '')}
                key={index}
                onClick={() => setSelected(index)}
              >
                {item.cornerMark ? <span className={styles.cornerMark}>{item.cornerMark}</span> : null}
                <span className={styles.desc}>{item.pDesc}</span>
                <div className={styles.price}>
                  <span>$</span>
                  <span>{(item.usdPrice / 100).toFixed(1)}</span>
                </div>
                {item.tagMark ? <p className={styles.popular}>{item.tagMark}</p> : null}
                <p className={styles.discountMark}>{item.discountMark}</p>
              </div>
            )
          })}
        </div>
        <div className={styles.vipChoose}>
          <img loading="lazy" src="/images/vip.png" alt="vip" />
          <span className={styles.span1}>请选择支付方式</span>
        </div>
        <div className={styles.vipPayWay}>
          {payArr.map((item, index) => {
            return (
              <div
                className={cm(styles.payWayItem, payType === item.value ? styles.active : '')}
                key={index}
                onClick={() => setPayType(item.value)}
              >
                <img loading="lazy" src={item.icon} alt={item.name} />
                <span>{item.name}</span>
              </div>
            )
          })}
        </div>
        <div className={styles.vipPayWay}>
          {MaLaiArr.map((item, index) => {
            return (
              <div
                className={cm(styles.payWayItem, payType === item.value ? styles.active : '')}
                key={index}
                onClick={() => setPayType(item.value)}
              >
                <img loading="lazy" src={item.icon} alt={item.name} />
                <span>{item.name}</span>
              </div>
            )
          })}
        </div>
        {payType === 3 ? (
          <Button className={cm(styles.btnOpen, isLoading ? 'opacity-80' : 'opacity-100')} onClick={toPaypal}>
            {isLoading ? <FetchLoading /> : null}
            <span>开通VIP</span>
          </Button>
        ) : null}
      </div>
      <div className={cm(styles.vipRight, payType !== 3 ? '' : styles.vipRightHidden)}>
        <p className={styles.tips}>请使用手机扫码支付</p>
        <div className={styles.qrcodeBox}>
          <canvas ref={refQrcode} className={styles.qrcode}></canvas>
          {paySuccess ? (
            <div className={styles.paySuccess}>
              <img loading="lazy" src="/images/pay_success.png" alt="支付成功" />
              <p className={styles.payDesc}>订单支付成功！</p>
              <p className={styles.payTips}>3 秒之后关闭弹窗</p>
            </div>
          ) : null}
          {isLoading ? <Loading /> : null}
        </div>
      </div>
    </Dialog>
  )
}

export default Index
